package cn.gson.springboot.model.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;

import cn.gson.springboot.model.dao.DrugsYkDao;
import cn.gson.springboot.model.dao.InventoryYkDAO;
import cn.gson.springboot.model.dao.ReturnDetailsYkDAO;
import cn.gson.springboot.model.dao.ReturnDrugsYkDAO;
import cn.gson.springboot.model.mapper.ReturnDrugsYkMapper;
import cn.gson.springboot.model.pojos.InventoryYk;
import cn.gson.springboot.model.pojos.ReturnDetailsYk;
import cn.gson.springboot.model.pojos.ReturnDrugsYk;
import cn.gson.springboot.model.vo.ReturnDrugsYkVO;

@Service
@Transactional(rollbackFor=Exception.class)
public class ReturnDrugsYkService {
	@Autowired
	private ReturnDrugsYkMapper rdm;
	@Autowired
	private ReturnDrugsYkDAO rddao;
	@Autowired
	private DrugsYkDao hdao;
	@Autowired
	private ReturnDetailsYkDAO rdsdao;
	@Autowired
	private InventoryYkDAO itd;
	
	//查询所有
	public JSONArray findtuihuo(Integer return_drugs_id) {
		return rdm.findtuihuo(return_drugs_id);
	}
	
	//修改状态
	public ReturnDrugsYk idxgzt(Integer returnDrugsId) {
		return rddao.xiugaizt(returnDrugsId);
	}
	
	//新增
	public ReturnDrugsYk adds(ReturnDrugsYk d) {
		return rddao.save(d);
	}
	
	//主从表新增
	public void saveOrder(ReturnDrugsYkVO rdvo) {
		//获取采购订单进行新增
		ReturnDrugsYk tuihuo = rdvo.getTuihuo();
		tuihuo.setReturnStatic("未退货");
		tuihuo.setReturnDrugsTime(new Date());

		ReturnDrugsYk save = rddao.save(tuihuo);
		
		List<ReturnDetailsYk> details = rdvo.getTuihuoxq();
		//循环
		for (ReturnDetailsYk pur : details) {
			//添加订单信息
			pur.setReturnDrugsYk(tuihuo);
			//查询库存
			InventoryYk inventory = itd.findById(pur.getInventoryYk().getInventoryYkId()).get();
			//重新赋值一下药品对象
			pur.setInventoryYk(inventory);
			pur.setReturnDenumber(pur.getReturnDenumber());
			rdsdao.save(pur);
		}
		
		
		//pddao.saveAll(details);
	}
}
